package com.pan.service.impl;

import com.pan.config.common.SeckillRabbitmqCommon;
import com.pan.entity.Result;
import com.pan.enume.ResultEnum;
import com.pan.excep.enume.ErrorCode;
import com.pan.excep.error.ServiceException;
import com.pan.service.SeckillCouponService;
import com.pan.tools.RedisTools;
import io.swagger.models.auth.In;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.Map;

@Service("seckillCouponService")
public class SeckillCouponServiceImpl implements SeckillCouponService {

    @Resource
    private RabbitTemplate rabbitTemplate;

    @Resource
    private RedisTools redisTools;

    /**
     *
     * map:
     *      seckillTime:
     *      userTicket:
     *      couponId:
     *
     * @param userTicket
     * @param couponId
     * @return
     */
    @Override
    public Result seckillCoupon(String userTicket,Long couponId){

        Map map = new HashMap();
        Timestamp seckillTime = new Timestamp(System.currentTimeMillis());
        map.put("seckillTime",seckillTime);
        map.put("userTicket",userTicket);
        map.put("couponId",couponId);
        try {
            rabbitTemplate.convertAndSend(
                    SeckillRabbitmqCommon.RABBITMQ_SECKILL_COUPON_DIRECT_EXCHANGE,
                    SeckillRabbitmqCommon.RABBITMQ_SECKILL_COUPON_DIRECT_ROUTING,
                    map);
            return new Result(ResultEnum.SUCCESS);
        }
        catch (Exception e){
            throw new ServiceException(ErrorCode.RABBITMQ_INSERT_ERROR);
        }
    }

    @Override
    public Result<Integer> getCount(Long couponId){
        Boolean isCoupon = redisTools.exists("seckillCoupon:"+couponId).getData();
        if (!isCoupon){
            return new Result(ResultEnum.NOT_FOUND_ERROR);
        }
        Integer couponCount = Integer.parseInt((String) redisTools.hget("seckillCoupon:"+couponId,"count").getData());
        Result<Integer> result = new Result<>(ResultEnum.SUCCESS);
        result.setData(couponCount);
        return result;
    }

}
